package com.topone.service.impl;

import com.topone.Const.Model;
import com.topone.Enum.NotificationEnum;
import com.topone.Exception.FanZoneException;
import com.topone.Exception.FanZoneServiceException;
import com.topone.Utils.MathUtil;
import com.topone.dataObject.Balance;
import com.topone.dataObject.Bussiness;
import com.topone.dataObject.Mapper.BussinessMapper;
import com.topone.dataObject.PayNotification;
import com.topone.dataObject.ShopApply;
import com.topone.dto.BussinessDTO;
import com.topone.dto.TcCouponDTO;
import com.topone.repository.BalanceRepository;
import com.topone.repository.BussinessRepository;
import com.topone.repository.ShopApplyRepository;
import com.topone.service.BussinessService;
import com.topone.service.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/11/6,0006.
 */
@Service
@Slf4j
public class BussinessServiceImpl implements BussinessService {

    @Autowired
    private BussinessRepository repository;

    @Autowired
    private ShopApplyRepository shopApplyRepository;

    @Autowired
    private NotificationService notificationService;


    @Autowired
    private BussinessMapper bussinessMapper;

    @Autowired
    private BussinessService bussinessService;

    @Autowired
    private BalanceRepository balanceRepository;

    //根据商家名称模糊查询
    @Override
    public List<BussinessDTO> findBussinessNameList(Bussiness bussiness) {

        return bussinessMapper.businessNameList(bussiness);

    }

    //根据id查询商家信息
    @Override
    public Bussiness findOne(String bussinessCode, String bussinessId) {
        return repository.findByBussinessCodeAndBussinessId(bussinessCode, bussinessId);
    }

    @Override
    public Bussiness getOne(String id) {
        return repository.getOne(id);
    }

    //根据商家名称查询
    @Override
    public List<BussinessDTO> findByBussinessCode(Bussiness bussiness) {
        return bussinessMapper.businessCodeList(bussiness);
    }

    //查询所有的商家信息
    @Override
    public List<Bussiness> findAll() {
        List<Bussiness> bussinessList = repository.findAll();
        return bussinessList;
    }

    //修改或新增商家信息
    @Override
    @Transactional
    public Bussiness save(Bussiness bussiness, ShopApply shopApply) {
        if (shopApply != null) {
            if (StringUtils.isNotEmpty(shopApply.getShopId())) {
                shopApplyRepository.save(shopApply);
            }
        }
        return repository.save(bussiness);
    }

    //查询一个商家所有的店铺信息
    @Override
    public List<Bussiness> findList(String bussinessCode) {
        return repository.findByBussinessCode(bussinessCode);
    }

    //查询所有已入驻商家
    @Override
    public List<Bussiness> findUpAll(Integer bussinessStatus) {
        return repository.findByBussinessStatus(bussinessStatus);
    }

    //查询所有有效商家信息
    @Override
    public List<BussinessDTO> allBussiness(Integer status) {
        List<BussinessDTO> list = bussinessMapper.allBussiness(status);
        List<BussinessDTO> bussinessDTOS = new ArrayList<>();
        list.forEach(bussinessDTO -> {
            if (CollectionUtils.isNotEmpty(bussinessDTO.getCouponList())) {
                List<TcCouponDTO> tcCouponDTOS = bussinessDTO.getCouponList().stream().filter(tcCouponDTO ->
                        tcCouponDTO.getCouponStatus() == 0).collect(Collectors.toList());
                bussinessDTO.setCouponList(tcCouponDTOS);
            }
            bussinessDTOS.add(bussinessDTO);
        });
        return bussinessDTOS;
    }

    //查询所有有效商家信息
    @Override
    public List<BussinessDTO> list(Integer status) {
        return bussinessMapper.list(status);
    }

    @Override
    public BussinessDTO checkBussinessPassword(String bussinessPassword, String bussinessPhone) {
        return bussinessMapper.findBussinessId(bussinessPassword, bussinessPhone);
    }

    @Override
    public List<BussinessDTO> findBusinessNameList(String businessName) {
        return bussinessMapper.findBussinessByBussinessNameLike(businessName);
    }

    @Override
    public Bussiness findByPhone(String phone) {
        return repository.findByBussinessPhone(phone);
    }

    @Override
    @Transactional
    public Map<String, Object> bussinessBalance(String bussinessId, String bussinessCode, String flag) {
        Map<String, Object> map = new HashMap<>();
        double amount = 0;
        Integer orderNum = 0;
        Bussiness bussiness = findOne(bussinessCode, bussinessId);
        try {
            if (Objects.nonNull(bussiness) && StringUtils.isNotEmpty(bussiness.getBussinessId())) {
                List<PayNotification> payNotificationList =
                        notificationService.findListByBussinessId(bussinessId, NotificationEnum.NO.getCode(), Model.BALANCE_TYPE);
                if (Objects.nonNull(payNotificationList)) {
                    Integer fee = 0;
                    for (int i = 0; i < payNotificationList.size(); i++) {
                        if (payNotificationList.get(i).getTotalFee() != null) {
                            fee += payNotificationList.get(i).getTotalFee();
                        } else {
                            continue;
                        }
                        if (StringUtils.equals("balance", flag)) {
                            payNotificationList.get(i).setStatus(NotificationEnum.YES.getCode());
                            notificationService.save(payNotificationList.get(i));
                        }
                    }
                    amount = MathUtil.Fen2Yuan(fee);
                    orderNum = payNotificationList.size();
                    map.put("amount", amount);
                    map.put("orderNum", orderNum);
                    if (amount > 0) {
                        if (StringUtils.equals("balance", flag)) {
                            bussiness.setTotalFee(new BigDecimal(bussiness.getTotalFee().doubleValue() + amount));
                            bussinessService.save(bussiness, null);
                            Balance balance = new Balance();
                            balance.setBalance(new BigDecimal(amount));
                            balance.setTotalFee(bussiness.getTotalFee());
                            balanceRepository.save(balance);
                        }

                    }
                    return map;
                } else {
                    return null;
                }
            } else {
                log.debug("商家不存在");
                return null;
            }
        } catch (FanZoneException e) {
            throw new FanZoneServiceException("商家资金结算失败");
        }

    }
}